let $ = window.$ = require('jquery');
require('./index.css');

if (process.env.NODE_ENV === 'development') {
    let oResult = $('#result');
    let startTip = $('#start-tip');
    let startTipJson = {
        one: startTip.find('.j-one'),
        two: startTip.find('.j-two')
    };

    let autoAgencyList = JSON.parse(localStorage.autoAgencyList || '{}');
    if (autoAgencyList['/one']) {
        startTipJson.one.html('one start');
    }
    if (autoAgencyList['/two']) {
        startTipJson.two.html('two start');
    }
    let refreshTip = $('#refresh-tip');
    let refreshTipJson = {
        one: refreshTip.find('.j-one'),
        two: refreshTip.find('.j-two')
    };

    if (localStorage.isAutoRefreshOne === 'true') {
        refreshTipJson.one.html('one start');
    }
    if (localStorage.isAutoRefreshTwo === 'true') {
        refreshTipJson.two.html('two start');
    }

    let pathGroups = $('.j-path-group');
    (localStorage.pathGroupsOne || '').split(',').forEach(item => {
        pathGroups.eq(0).append($(`<option value="${item}">${item}</option>`));
    });
    (localStorage.pathGroupsTwo || '').split(',').forEach(item => {
        pathGroups.eq(1).append($(`<option value="${item}">${item}</option>`));
    });

    let stateDoms = $('.j-state');
    stateDoms.each(index => {
        let list = localStorage.apiStatus.split(',');
        stateDoms.eq(index).html(`
            <option value="">无</option>
            ${list.map(prop => `<option value="${prop}">${prop}</option>`)}
        `);
    });

    $('.j-startAgency').click((e) => { // 切换代理的开启状态
        let eType = $(e.target).attr('e-type');
        $.ajax({
            url: `/${eType}/agency-change-agency`,
            success: function (data) {
                autoAgencyList['/' + eType] = data.isOpen;

                localStorage.autoAgencyList = JSON.stringify(autoAgencyList);
                startTipJson[eType].html(data.isOpen ? `${eType} start` : '');
            }
        });
    });

    $('.j-testStart').click((e) => {
        let eType = $(e.target).attr('e-type');
        $.ajax({
            url: `/${eType}/user/info`,
            data: {
                userName: 'Lone',
                age: 20,
                grade: 30
            },
            success: function (data) {
                console.log(data);
                oResult.text(JSON.stringify(data,null,4));
            }
        });
    });

    $('.j-ws').click(function(e){
        // 目前 ws 还不能处理
        e.preventDefault();
        // 这里的port与proxy里的一致
        let oWS = new WebSocket(`ws://${window.location.hostname}:${18474}/ws/test?name=test`);
        oWS.onopen = function(){
            oWS.send('你好，websocket');
        };
        oWS.onmessage = function(e){
            oResult.text(e.data);
        };

        setTimeout(() => {
            oWS.send('又发消息，websocket');
        }, 3000)
    });
}
